/*
 * Copyright 2011 J. Auer, J. Andert, F.-J. Jendrusch, U. Celebi
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.fuberlin.replication;

import de.fuberlin.replication.application.Synchronizable;
import de.fuberlin.replication.library.VectorSets;

/**
 * Class for accessing the methods needed to implement the synchronization framework into an application. Every time
 * some datum, that is managed by the application, changes, <code>update</code> has to be called, to report the change
 * to the framework. Then, synchronization with a remote device can be done.
 */
public final class Replication {
	private Replication() {
	}

	/**
	 * Synchronize with a connected remote device. Every access to the communication and storage interfaces is done via
	 * the given <code>Synchronizable</code>.
	 * 
	 * @param synchronizable Class implementing <code>Synchronizable</code>
	 * @return True if synchronization was successful and complete, false if synchronization was successful but not
	 *         complete. If synchronization failed, <code>onSynchronizationException</code> is called
	 */
	public static boolean synchronize(Synchronizable synchronizable) {
		synchronized (synchronizable.getClass()) {
			try {
				synchronizable.onSynchronizationStart();

				return VectorSets.synchronize(synchronizable);
			} catch (Exception e) {
				synchronizable.onSynchronizationException(e);

				return false;
			} finally {
				synchronizable.onSynchronizationStop();
			}
		}
	}

	/**
	 * Report a change of the persistent data to the synchronization library.
	 * 
	 * @param synchronizable Class implementing <code>Synchronizable</code>
	 * @param name Unique identifier of the changed datum
	 */
	public static void update(Synchronizable synchronizable, String name) {
		synchronized (synchronizable.getClass()) {
			try {
				synchronizable.onUpdateStart(name);

				VectorSets.update(synchronizable, name);
			} catch (Exception e) {
				synchronizable.onUpdateException(name, e);
			} finally {
				synchronizable.onUpdateStop(name);
			}
		}
	}
}